package org.jeecg.modules.zhouAdmin.admin.goodsCenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.mapper.MySysUserMapper;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.pojo.MySysUser;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.mapper.*;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.pojo.*;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.service.IGoodsCenterService;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.util.GoodsUtil;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.util.ZXingutil;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccCompanyInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccCompanyInfo;
import org.jeecg.modules.zhoupackage.mapper.MyMlccCategoryInfoMapper;
import org.jeecg.modules.zhoupackage.pojo.MlccCategoryInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 商品中心Service
 */
@Service
public class GoodsCenterServiceImpl implements IGoodsCenterService {

    @Autowired
    MyMlccThirdGoodsTypeMapper goodsTypeMapper;

    @Autowired
    MyMlccThirdGoodsSeriesMapper goodsSeriesMapper;

    @Autowired
    MyMlccThirdGoodsRangeMapper rangeMapper;

    @Autowired
    MyMlccThirdGoodsMapper goodsMapper;

    @Autowired
    MyMlccThirdGoodsBookletMapper bookletMapper;

    @Autowired
    MyMlccThirdGoodsBookletFaMapper bookletFaMapper;

    @Autowired
    MyMlccCompanyInfoMapper companyInfoMapper;

    @Autowired
    MyMlccThirdGoodsAndBookletMapper goodsAndBookletMapper;

    @Autowired
    MyMlccThirdGoodstypeParameterMapper goodstypeParameterMapper;

    @Autowired
    MyMlccThirdGoodsandparameterMapper goodsandparameterMapper;

    @Autowired
    MyMlccThirdGoodsFanxiuMapper fanxiuMapper;

    @Autowired
    MyMlccThirdGoodsSpecificationsMapper guigeMapper;

    @Autowired
    MyMlccThirdGoodsSizeMapper sizeMapper;

    @Autowired
    GoodsUtil goodsUtil;

    @Autowired
    MySysUserMapper userMapper;

    @Autowired
    ZXingutil zXingutil;

    @Autowired
    MyMlccCategoryInfoMapper categoryInfoMapper;

    /**
     * 获取商品类型列表
     *
     * @param page 分页
     * @param code 编号
     */
    @Override
    public IPage<MlccThirdGoodsType> listGoodsTypes(Page<MlccThirdGoodsType> page, String code) {
        QueryWrapper<MlccThirdGoodsType> wrapper = new QueryWrapper<>();
        if (code != null && !"".equals(code)) {
            wrapper.like("goods_type_code", code);
        }
        wrapper.orderByAsc("numbers");
        return goodsTypeMapper.selectPage(page, wrapper);
    }

    /**
     * 新增商品类型
     *
     * @param goodsType 商品类型对象
     */
    @Override
    public int addGoodType(MlccThirdGoodsType goodsType) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<MlccThirdGoodsType> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_type_code", goodsType.getGoodsTypeCode());
        int count = goodsTypeMapper.selectCount(wrapper);
        if (count > 0) {
            return -1; // 商品类型编号重复
        }
        QueryWrapper<MlccThirdGoodsType> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("goods_type_name", goodsType.getGoodsTypeName());
        int count2 = goodsTypeMapper.selectCount(wrapper2);
        if (count2 > 0) {
            return -1; // 商品类型名称重复
        }
        goodsType.setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
        return goodsTypeMapper.insert(goodsType);
    }

    /**
     * 编辑商品类型
     *
     * @param goodsType 商品类型对象
     */
    @Override
    public int updateGoodType(MlccThirdGoodsType goodsType) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<MlccThirdGoodsType> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_type_code", goodsType.getGoodsTypeCode());
        List<MlccThirdGoodsType> list = goodsTypeMapper.selectList(wrapper);
        if (list != null && list.size() > 0) {
            for (MlccThirdGoodsType type : list) {
                if (!type.getId().equals(goodsType.getId()) && type.getGoodsTypeName().equals(goodsType.getGoodsTypeName())) {
                    return -1; // 商品类型名称或编号重复
                }
                if (!type.getId().equals(goodsType.getId()) && type.getGoodsTypeCode().equals(goodsType.getGoodsTypeCode())) {
                    return -1; // 商品类型名称或编号重复
                }
            }
        }
        goodsType.setUpdateBy(user.getRealname());
        return goodsTypeMapper.updateById(goodsType);
    }

    /**
     * 删除商品类型
     *
     * @param id 商品类型id
     */
    @Override
    public int delGoodType(String id) {
        return goodsTypeMapper.deleteById(id);
    }

    /**
     * 商品系列列表
     *
     * @param page
     * @param typeid 商品类型id
     * @param name   系列名称
     * @param status 状态
     */
    @Override
    public IPage<MlccThirdGoodsSeries> listGoodsGroup(Page<MlccThirdGoodsSeries> page, String typeid, String name, Integer status) {
        QueryWrapper<MlccThirdGoodsSeries> wrapper = new QueryWrapper<>();
        if (typeid != null && !"".equals(typeid)) {
            wrapper.eq("goods_type_id", typeid);
        }
        if (name != null && !"".equals(name)) {
            wrapper.like("series_name", name);
        }
        if (status != null) {
            wrapper.eq("status", status);
        } else {
            wrapper.in("status", 0, 2);
        }
        wrapper.orderByDesc("create_time");
        IPage<MlccThirdGoodsSeries> iPage = goodsSeriesMapper.selectPage(page, wrapper);
        List<MlccThirdGoodsSeries> records = iPage.getRecords();
        // 查询系列下的商品数量
        if (records != null && records.size() > 0) {
            for (MlccThirdGoodsSeries record : records) {
                QueryWrapper<MlccThirdGoods> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("goods_series_id", record.getId()).ne("status", 1);
                int count = goodsMapper.selectCount(wrapper1);
                record.setCount(count);
            }
        }
        return iPage;
    }

    /**
     * 新增商品系列
     *
     * @param entity 商品系列对象
     */
    @Override
    public int addGoodGroup(MlccThirdGoodsSeries entity) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        entity.setCreateBy(user.getRealname()).setUpdateBy(user.getRealname()).setStatus(2);
        return goodsSeriesMapper.insert(entity);
    }

    /**
     * 编辑商品系列
     *
     * @param entity 商品系列对象
     */
    @Override
    public int updateGoodGroup(MlccThirdGoodsSeries entity) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        entity.setUpdateBy(user.getRealname());
        return goodsSeriesMapper.updateById(entity);
    }

    /**
     * 下架商品系列
     *
     * @param id 商品系列id
     */
    @Override
    public int offGoodGroup(String id) {
        MlccThirdGoodsSeries goodsSeries = goodsSeriesMapper.selectById(id);
        if (goodsSeries != null) {
            goodsSeries.setStatus(2);
        }
        return goodsSeriesMapper.updateById(goodsSeries);
    }

    /**
     * 上架商品系列
     *
     * @param id 商品系列id
     */
    @Override
    public int upGoodGroup(String id) {
        MlccThirdGoodsSeries goodsSeries = goodsSeriesMapper.selectById(id);
        if (goodsSeries != null) {
            goodsSeries.setStatus(0);
        }
        return goodsSeriesMapper.updateById(goodsSeries);
    }

    /**
     * 删除商品系列
     *
     * @param id 商品系列id
     */
    @Override
    public int delGoodGroup(String id) {
        MlccThirdGoodsSeries goodsSeries = goodsSeriesMapper.selectById(id);
        if (goodsSeries != null) {
            if (goodsSeries.getStatus() == 0) {
                return -1;
            }
            goodsSeries.setStatus(1);
        }
        return goodsSeriesMapper.updateById(goodsSeries);
    }

    /**
     * 获取商品系列的阶梯售价
     *
     * @param groupid 商品系列ID
     */
    @Override
    public List<MlccThirdGoodsRange> listGroupPrice(String groupid) {
        QueryWrapper<MlccThirdGoodsRange> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_series_id", groupid);
        return rangeMapper.selectList(wrapper);
    }

    /**
     * 添加阶梯售价
     *
     * @param entity 参数对象
     */
    @Override
    public int saveGroupPrice(MlccThirdGoodsRange entity) {
        if (entity.getMin() >= entity.getMax()) {
            return -1;
        }
        QueryWrapper<MlccThirdGoodsRange> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_series_id", entity.getGoodsSeriesId());
        List<MlccThirdGoodsRange> prices = rangeMapper.selectList(wrapper);
        if (prices != null && prices.size() > 0) {
            for (MlccThirdGoodsRange price : prices) {
                if (entity.getMin() >= price.getMin() && entity.getMin() < price.getMax()) {
                    return -1;
                }
            }
        }
        return rangeMapper.insert(entity);
    }

    /**
     * 删除商品系列阶梯价
     *
     * @param id 阶梯价主键id
     */
    @Override
    public int deleteGroupPrice(String id) {
        return rangeMapper.deleteById(id);
    }

    /**
     * 获取商品类型的下拉列表
     */
    @Override
    public List<MlccThirdGoodsType> laGoodsType() {
        QueryWrapper<MlccThirdGoodsType> wrapper = new QueryWrapper<>();
        wrapper.ne("id", 1);
        return goodsTypeMapper.selectList(wrapper);
    }

    /**
     * 获取商品列表
     *
     * @param page
     * @param code    商品编号
     * @param gyscode 供应商编号
     * @param status  状态
     */
    @Override
    public IPage<MlccThirdGoods> listGoods(Page<MlccThirdGoods> page, String code, String gyscode, Integer status, String groupID) {
        QueryWrapper<MlccThirdGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_series_id", groupID).eq("is_main", 0).eq("is_good", 0);
        if (code != null && !"".equals(code)) {
            wrapper.like("goods_code", code);
        }
        if (gyscode != null && !"".equals(gyscode)) {
            wrapper.like("supplier_goods_code", gyscode);
        }
        if (status != null) {
            wrapper.eq("status", status);
        } else {
            wrapper.in("status", 0, 2);
        }
        IPage<MlccThirdGoods> iPage = goodsMapper.selectPage(page, wrapper);
        List<MlccThirdGoods> list = iPage.getRecords();
        if (list != null && list.size() > 0) {
            // 遍历查询供应商
            for (MlccThirdGoods thirdGoods : list) {
                MySysUser sysUser = userMapper.selectById(thirdGoods.getSupplierId());
                if (sysUser != null) {
                    thirdGoods.setRealname(sysUser.getRealname());
                }
            }
        }
        return iPage;
    }

    /**
     * 下架商品
     *
     * @param id 商品id
     */
    @Override
    public int offGoods(String id) {
        MlccThirdGoods pproduct = goodsMapper.selectById(id);
        pproduct.setStatus(2);
        int i = goodsMapper.updateById(pproduct);
        if (i > 0) {
            // 如过下架商品，删除产品表中对应的现货
            goodsUtil.delXianhuo(pproduct);
        }
        return i;
    }

    /**
     * 上架商品
     *
     * @param id 商品id
     */
    @Override
    public int upGoods(String id) {
        MlccThirdGoods pproduct = goodsMapper.selectById(id);
        pproduct.setStatus(0);
        int i = goodsMapper.updateById(pproduct);
        //商品启用成功，向产品表添加一条记录，现货产品
        if (i > 0) {
            goodsUtil.addXianhuo(pproduct);
        }
        return i;
    }

    /**
     * 删除商品
     *
     * @param id 商品id
     */
    @Override
    public int delGoods(String id) {
        MlccThirdGoods pproduct = goodsMapper.selectById(id);
        if (pproduct.getStatus() == 0) {
            return -1;
        }
        pproduct.setStatus(1);
        int i = goodsMapper.updateById(pproduct);
        if (i > 0) {
            // 如过下架商品，删除产品表中对应的现货
            goodsUtil.delXianhuo(pproduct);
        }
        return i;
    }

    /**
     * 获取商品册列表
     *
     * @param page  分页器
     * @param name  客户名称
     * @param phone 联系电话
     */
    @Override
    public IPage<MlccThirdGoodsBooklet> listBooklets(Page<MlccThirdGoodsBooklet> page, String name, String phone) {
        QueryWrapper<MlccThirdGoodsBooklet> wrapper = new QueryWrapper<>();
        if (name != null && !"".equals(name)) {
            wrapper.like("booklet_name", name);
        }
        return bookletMapper.selectPage(page, wrapper);
    }

    /**
     * 新增商品册
     *
     * @param booklet 商品册对象
     */
    @Override
    public int saveBooklet(MlccThirdGoodsBooklet booklet) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        booklet.setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                .setSysOrgCode(user.getOrgCode());
        return bookletMapper.insert(booklet);
    }

    /**
     * 更新商品册
     *
     * @param booklet 商品册对象
     */
    @Override
    public int updateBooklet(MlccThirdGoodsBooklet booklet) {
        return bookletMapper.updateById(booklet);
    }

    /**
     * 获取主推面料列表
     *
     * @param page    分页
     * @param code    商品编号
     * @param gysCode 供应商编号
     * @param status  状态
     */
    @Override
    public IPage<MlccThirdGoods> getFirstGoodsList(Page<MlccThirdGoods> page, String code, String gysCode, String status) {
        QueryWrapper<MlccThirdGoods> wrapper = new QueryWrapper<>();
        wrapper.ne("status", 1).eq("is_main", 1);
        if (null != code && !"".equals(code)) {
            wrapper.like("goods_code", code);
        }
        if (null != gysCode && !"".equals(gysCode)) {
            wrapper.like("supplier_goods_code", gysCode);
        }
        if (null != status && !"".equals(status)) {
            wrapper.eq("status", status);
        }
        return goodsMapper.selectPage(page, wrapper);
    }

    /**
     * 新增主推商品
     *
     * @param code   商品编号
     * @param price  添加的价格
     * @param remark 备注
     */
    @Override
    public int addFirstGoods(String code, double price, String remark) {
        QueryWrapper<MlccThirdGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_code", code);
        MlccThirdGoods info = goodsMapper.selectOne(wrapper);
        if (info == null) return -1;// 商品不存在
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 设置为主推商品之后，把这个商品移出商品系列(不行)
        info.setUpdateBy(user.getRealname()).setPrice(new BigDecimal(price)).setRemark(remark)
                .setIsMain(1);
        return goodsMapper.updateById(info);
    }

    /**
     * 商品册发放情况
     *
     * @param bookletid 商品册id
     * @param page      分页器
     */
    @Override
    public IPage<MlccThirdGoodsBookletFa> listFafang(String bookletid, Page<MlccThirdGoodsBookletFa> page) {
        QueryWrapper<MlccThirdGoodsBookletFa> wrapper = new QueryWrapper<>();
        wrapper.eq("booklet_id", bookletid);
        IPage<MlccThirdGoodsBookletFa> iPage = bookletFaMapper.selectPage(page, wrapper);
        List<MlccThirdGoodsBookletFa> list = iPage.getRecords();
        if (list != null && list.size() > 0) {
            for (MlccThirdGoodsBookletFa bookletFa : list) {
                MlccCompanyInfo companyInfo = companyInfoMapper.selectById(bookletFa.getCompanyId());
                if (companyInfo != null) {
                    bookletFa.setCompanyName(companyInfo.getCompanyName()).setCompanyCode(companyInfo.getCompanyCode())
                            .setAboutPhone(companyInfo.getAboutPhone());
                }
            }
        }
        return iPage;
    }

    /**
     * 商品册详情
     *
     * @param id 商品册id
     */
    @Override
    public MlccThirdGoodsBooklet bookletDetail(String id) {
        return bookletMapper.selectById(id);
    }

    /**
     * 发放商品册
     *
     * @param bookletid  商品册id
     * @param remark     备注
     * @param num        发放数量
     * @param companyids 公司id
     */
    @Override
    public int addFa(String bookletid, String remark, Integer num, String[] companyids) {
        if (companyids == null && companyids.length == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccThirdGoodsBooklet booklet = bookletMapper.selectById(bookletid);
        if (booklet.getResidueNum() < num) {
            return -1;
        }
        if (booklet != null) {
            for (String companyid : companyids) {
                MlccCompanyInfo companyInfo = companyInfoMapper.selectById(companyid);
                if (companyInfo != null) {
                    if (booklet.getResidueNum() < num) {
                        throw new RuntimeException("面料册数量不足，无法发放！");
                    }
                    MlccThirdGoodsBookletFa bookletFa = new MlccThirdGoodsBookletFa();
                    bookletFa.setCompanyId(companyInfo.getId() + "").setBookletId(booklet.getId() + "")
                            .setNumber(num).setPrice(booklet.getPrice()).setAllPrice(booklet.getPrice()
                            .multiply(new BigDecimal(num))).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                            .setRemark(remark);
                    int insert = bookletFaMapper.insert(bookletFa);
                    if (insert == 0) {
                        return 0;
                    } else {
                        System.out.println("发放数量=" + booklet.getIssueNum());
                        System.out.println("剩余数量=" + booklet.getResidueNum());
                        booklet.setIssueNum(booklet.getIssueNum() + num).setResidueNum(booklet.getResidueNum() - num);
                        bookletMapper.updateById(booklet);
                    }
                }
            }
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 删除发放记录
     *
     * @param id 发放id
     */
    @Override
    public int deleteFa(String id) {
        int result = 0;
        MlccThirdGoodsBookletFa bookletFa = bookletFaMapper.selectById(id);
        if (bookletFa != null) {
            // 面料车册数量恢复
            MlccThirdGoodsBooklet booklet = bookletMapper.selectById(bookletFa.getBookletId());
            result = bookletFaMapper.deleteById(id);
            if (result > 0) {
                booklet.setResidueNum(booklet.getResidueNum() + bookletFa.getNumber())
                        .setIssueNum(booklet.getIssueNum() - bookletFa.getNumber());
                bookletMapper.updateById(booklet);
            }
        }
        return result;
    }

    /**
     * 获取商品册下的商品列表
     *
     * @param page      分页器
     * @param bookletid 商品册id
     */
    @Override
    public IPage<MlccThirdGoods> listFabricFromBooklet(Page<MlccThirdGoods> page, String bookletid) {
        ArrayList<String> goodslist = new ArrayList<>();
        QueryWrapper<MlccThirdGoodsAndBooklet> wrapper = new QueryWrapper<>();
        wrapper.eq("boolet_id", bookletid);
        // 面料册下所有的面料关联记录
        List<MlccThirdGoodsAndBooklet> andFabrics = goodsAndBookletMapper.selectList(wrapper);
        if (andFabrics != null && andFabrics.size() > 0) {
            for (MlccThirdGoodsAndBooklet andFabric : andFabrics) {
                goodslist.add(andFabric.getGoodsId());
            }
        }
        QueryWrapper<MlccThirdGoods> wrapper1 = new QueryWrapper<>();
        if (goodslist.size() > 0) {
            wrapper1.in("id", goodslist);
        } else {
            wrapper1.eq("id", -1);
        }
        IPage<MlccThirdGoods> iPage = goodsMapper.selectPage(page, wrapper1);
        // 赋予关联的id
        List<MlccThirdGoods> list = iPage.getRecords();
        if (list != null && list.size() > 0) {
            for (MlccThirdGoods goods : list) {
                QueryWrapper<MlccThirdGoodsAndBooklet> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("boolet_id", bookletid).eq("goods_id", goods.getId());
                MlccThirdGoodsAndBooklet one = goodsAndBookletMapper.selectOne(wrapper2);
                if (one != null) {
                    goods.setBookandid(one.getId());
                }
            }
        }
        return iPage;
    }

    /**
     * 删除商品册下的商品（删除关联信息）
     *
     * @param id 关联表id
     */
    @Override
    public int delFabricFrombook(String id) {
        return goodsAndBookletMapper.deleteById(id);
    }

    /**
     * 商品类型详情
     *
     * @param id 商品类型id
     */
    @Override
    public MlccThirdGoodsType typeDetail(Integer id) {
        return goodsTypeMapper.selectById(id);
    }

    /**
     * 新增商品类型参数
     *
     * @param param 参数对象
     * @param type  商品类型id
     */
    @Override
    public int saveTypeParam(MlccThirdGoodstypeParameter param, String type) {
        // 新增
        QueryWrapper<MlccThirdGoodstypeParameter> wrapper = new QueryWrapper<>();
        wrapper.eq("parameter_name", param.getParameterName()).eq("goods_type_id", type);
        MlccThirdGoodstypeParameter parameter = goodstypeParameterMapper.selectOne(wrapper);
        // 一个商品类型参数最多20个？？？
        QueryWrapper<MlccThirdGoodstypeParameter> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("goods_type_id", type);
        int count = goodstypeParameterMapper.selectCount(wrapper2);
        if (parameter == null) {
            if (count >= 20) {
                return -1;
            }
            // 执行新增
            param.setParameterCode(UUID.randomUUID().toString()).setGoodsTypeId(type);
            return goodstypeParameterMapper.insert(param);
        } else {
            return 0;
        }
    }

    /**
     * 获取类型下的参数列表
     *
     * @param type 商品类型id
     */
    @Override
    public List<MlccThirdGoodstypeParameter> listTypeParam(String type) {
        QueryWrapper<MlccThirdGoodstypeParameter> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_type_id", type);
        return goodstypeParameterMapper.selectList(wrapper);
    }

    /**
     * 更新商品类型参数
     *
     * @param param 参数数组
     */
    @Override
    public int updateTypeParam(MlccThirdGoodstypeParameter param) {
        MlccThirdGoodstypeParameter select = goodstypeParameterMapper.selectById(param.getId());
        if (select.getId().equals(param.getId())) {
            return 0;
        }
        return goodstypeParameterMapper.updateById(param);
    }

    /**
     * 删除商品类型参数
     *
     * @param id 参数id
     */
    @Override
    public int delTypeParam(String id) {
        return goodstypeParameterMapper.deleteById(id);
    }

    /**
     * 根据商品系例获取配置的参数
     *
     * @param groupid 商品系列id
     */
    @Override
    public List<MlccThirdGoodstypeParameter> paramlist(String groupid) {
        MlccThirdGoodsSeries goodsSeries = goodsSeriesMapper.selectById(groupid);
        QueryWrapper<MlccThirdGoodstypeParameter> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_type_id", goodsSeries.getGoodsTypeId());
        return goodstypeParameterMapper.selectList(wrapper);
    }

    /**
     * 根据商品系列获取商品类型
     *
     * @param group 商品系列id
     */
    @Override
    public MlccThirdGoodsType goodsTypeByGroup(String group) {
        MlccThirdGoodsSeries goodsSeries = goodsSeriesMapper.selectById(group);
        return goodsTypeMapper.selectById(goodsSeries.getGoodsTypeId());
    }

    /**
     * 进入新增商品界面，创建一条未启用的商品
     *
     * @param group 商品系列id
     */
    @Override
    public String createGoods(String group) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MlccThirdGoods goods = new MlccThirdGoods();
        goods.setId(UUID.randomUUID().toString()).setGoodsSeriesId(group);
        // 获取商品类型
        MlccThirdGoodsType type = goodsTypeByGroup(group);
        if (type != null) {
            goods.setGoodsTypeId(type.getId() + "").setStatus(1).setCreateBy(user.getRealname())
                    .setUpdateBy(user.getRealname());
        }
        int insert = goodsMapper.insert(goods);
        if (insert > 0) {
            return goods.getId();
        } else {
            throw new RuntimeException("创建商品失败了");
        }
    }

    /**
     * 给商品设置参数
     *
     * @param parameterId 参数id
     * @param paramvalue  参数值
     * @param goodsid     商品id
     */
    @Override
    public int saveGoodsParam(String parameterId, String paramvalue, String goodsid) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 新增之前先查询
        QueryWrapper<MlccThirdGoodsandparameter> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsid).eq("parameter_id", parameterId);
        MlccThirdGoodsandparameter selectOne = goodsandparameterMapper.selectOne(wrapper);
        if (selectOne == null) {
            // 新增
            MlccThirdGoodsandparameter goodsandparameter = new MlccThirdGoodsandparameter();
            goodsandparameter.setId(UUID.randomUUID().toString()).setGoodsId(goodsid)
                    .setParameterId(parameterId).setInputValue(paramvalue)
                    .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
            return goodsandparameterMapper.insert(goodsandparameter);
        } else {
            // 更新
            selectOne.setInputValue(paramvalue);
            return goodsandparameterMapper.updateById(selectOne);
        }
    }

    /**
     * 保存商品返修项
     *
     * @param fanxiu 返修项
     */
    @Override
    public int saveFanxiu(MlccThirdGoodsFanxiu fanxiu) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<MlccThirdGoodsFanxiu> wrapper = new QueryWrapper<>();
        wrapper.eq("fanxiu_name", fanxiu.getFanxiuName()).eq("goods_id", fanxiu.getGoodsId());
        MlccThirdGoodsFanxiu selectOne = fanxiuMapper.selectOne(wrapper);
        if (selectOne == null) {
            // 新增返修
            fanxiu.setId(UUID.randomUUID().toString()).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname())
                    .setFanxiuCode(UUID.randomUUID().toString());
            return fanxiuMapper.insert(fanxiu);
        } else {
            return -1;
        }
    }

    /**
     * 获取商品已设置的返修参数
     *
     * @param goodsid 商品id
     */
    @Override
    public List<MlccThirdGoodsFanxiu> listFanxiu(String goodsid) {
        QueryWrapper<MlccThirdGoodsFanxiu> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsid);
        return fanxiuMapper.selectList(wrapper);
    }

    /**
     * 删除返修参数
     *
     * @param id 返修id
     */
    @Override
    public int delFanxiu(String id) {
        return fanxiuMapper.deleteById(id);
    }

    /**
     * 商品规格批量导入
     *
     * @param list    excel中的数据
     * @param goodsid 商品ID
     */
    @Override
    public int importExcel(List<MlccThirdGoodsSpecifications> list, String goodsid) {
        if (list == null || list.size() == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int rsult = 0;
        for (MlccThirdGoodsSpecifications info : list) {
            Random random = new Random(9999);
            info.setId("S" + System.currentTimeMillis() + random.nextInt()).setGoodsId(goodsid).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
            rsult = guigeMapper.insert(info);
        }
        return rsult;
    }

    /**
     * 获取商品规格模板
     */
    @Override
    public List<MlccThirdGoodsSpecifications> exportGuige() {
        Page<MlccThirdGoodsSpecifications> page = new Page<>(1, 2);
        List<MlccThirdGoodsSpecifications> records = guigeMapper.selectPage(page, null).getRecords();
        return records;
    }

    /**
     * 查询已经设置的商品规格
     *
     * @param goodsid 商品id
     */
    @Override
    public List<MlccThirdGoodsSpecifications> listGuige(String goodsid) {
        QueryWrapper<MlccThirdGoodsSpecifications> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsid);
        return guigeMapper.selectList(wrapper);
    }

    /**
     * 删除已经设置的商品规格
     *
     * @param id 规格id
     */
    @Override
    public int delGuige(String id) {
        return guigeMapper.deleteById(id);
    }

    /**
     * 商品尺码批量导入
     *
     * @param list    excel中的数据
     * @param goodsid 商品ID
     */
    @Override
    public int importSizeExcel(List<MlccThirdGoodsSize> list, String goodsid) {
        if (list == null || list.size() == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int rsult = 0;
        for (MlccThirdGoodsSize info : list) {
            Random random = new Random(9999);
            info.setId("G" + System.currentTimeMillis() + random.nextInt()).setGoodsId(goodsid).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
            rsult = sizeMapper.insert(info);
        }
        return rsult;
    }

    /**
     * 获取商品尺码模板
     */
    @Override
    public List<MlccThirdGoodsSize> exportSize() {
        Page<MlccThirdGoodsSize> page = new Page<>(1, 2);
        List<MlccThirdGoodsSize> records = sizeMapper.selectPage(page, null).getRecords();
        return records;
    }

    /**
     * 查询已经设置的商品尺码
     *
     * @param goodsid 商品id
     */
    @Override
    public List<MlccThirdGoodsSize> listSize(String goodsid) {
        QueryWrapper<MlccThirdGoodsSize> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsid);
        return sizeMapper.selectList(wrapper);
    }

    /**
     * 删除已经设置的商品尺码
     *
     * @param id 尺码id
     */
    @Override
    public int delSize(String id) {
        return sizeMapper.deleteById(id);
    }

    /**
     * 更新商品
     *
     * @param goods 商品对象
     */
    @Override
    public int updateGoods(MlccThirdGoods goods) {
        // 插入之前先查询
        QueryWrapper<MlccThirdGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_code", goods.getGoodsCode());
        MlccThirdGoods one = goodsMapper.selectOne(wrapper);
        if (one != null && !one.getId().equals(goods.getId())) {
            return -1; // 编号重复
        }
        // 查询绑定的版号是否存在？
        QueryWrapper<MlccCategoryInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("category_code", goods.getPlateNumber()).eq("is_type", 3).ne("status", 1);
        MlccCategoryInfo categoryInfo = categoryInfoMapper.selectOne(wrapper1);
        if (categoryInfo == null) {
            return -2;
        }
        // 启用商品
        goods.setStatus(2);
        try {
            String path = zXingutil.encodeImg2(goods.getGoodsCode());
            goods.setCodeLink(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = goodsMapper.updateById(goods);
        /*if (i > 0) {
            // 统合表添加记录
            goodsUtil.addTonghe(goods.getId(), 0);
        }*/
        return i;
    }

    /**
     * 获取商品详情
     *
     * @param id 商品id
     */
    @Override
    public MlccThirdGoods goodsDetail(String id) {
        MlccThirdGoods goods = goodsMapper.selectById(id);
        // 获取商品类型
        MlccThirdGoodsType goodsType = goodsTypeMapper.selectById(goods.getGoodsTypeId());
        goods.setType(goodsType);
        return goods;
    }

    /**
     * 获取商品配置的参数
     *
     * @param id 商品id
     */
    @Override
    public List<MlccThirdGoodsandparameter> goodsParam(String id) {
        QueryWrapper<MlccThirdGoodsandparameter> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", id);
        List<MlccThirdGoodsandparameter> list = goodsandparameterMapper.selectList(wrapper);
        if (list != null && list.size() > 0) {
            for (MlccThirdGoodsandparameter param : list) {
                // 给每个参数查询参数名称
                MlccThirdGoodstypeParameter select = goodstypeParameterMapper.selectById(param.getParameterId());
                if (select != null) {
                    param.setParamName(select.getParameterName());
                }
            }
        }
        return list;
    }

    /**
     * 编辑商品参数
     *
     * @param param 参数对象
     */
    @Override
    public int updateGoodsParam(MlccThirdGoodsandparameter param) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        param.setUpdateBy(user.getRealname());
        return goodsandparameterMapper.updateById(param);
    }

    /**
     * 获取商品列表（导出）
     *
     * @param code    商品编号
     * @param gyscode 供应商编号
     * @param status  状态
     */
    @Override
    public List<MlccThirdGoods> exportGoods(String code, String gyscode, Integer status, String groupID) {
        QueryWrapper<MlccThirdGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_series_id", groupID);
        if (code != null && !"".equals(code)) {
            wrapper.like("goods_code", code);
        }
        if (gyscode != null && !"".equals(gyscode)) {
            wrapper.like("supplier_code", gyscode);
        }
        if (status != null) {
            wrapper.eq("status", status);
        } else {
            wrapper.in("status", 0, 2);
        }
        List<MlccThirdGoods> list = goodsMapper.selectList(wrapper);
        if (list != null && list.size() > 0) {
            // 遍历查询供应商
            for (MlccThirdGoods thirdGoods : list) {
                MySysUser sysUser = userMapper.selectById(thirdGoods.getSupplierId());
                if (sysUser != null) {
                    thirdGoods.setRealname(sysUser.getRealname());
                }
            }
        }
        return list;
    }

    /**
     * 商品批量导入
     *
     * @param list  excel中的数据
     * @param group 商品系列ID
     */
    @Override
    public int importGoods(List<MlccThirdGoods> list, String group) {
        // 如果是空文件
        if (list == null || list.size() == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int rsult = 0;
        MlccThirdGoodsSeries series = goodsSeriesMapper.selectById(group);
        for (MlccThirdGoods info : list) {
            // 插入之前先查询
            QueryWrapper<MlccThirdGoods> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_code", info.getGoodsCode());
            MlccThirdGoods one = goodsMapper.selectOne(wrapper);

            // 导入的供应商是名称，需要变成编号
            QueryWrapper<MySysUser> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("realname", info.getRealname().trim());
            MySysUser sysUser = userMapper.selectOne(wrapper1);
            if (sysUser != null) {
                info.setSupplierId(sysUser.getId());
            }
            try {
                String path = zXingutil.encodeImg(info.getGoodsCode());
                info.setCodeLink(path).setGoodsTypeId(series.getGoodsTypeId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (one == null) {
                // 插入
                info.setId(UUID.randomUUID().toString()).setUpdateBy(user.getRealname())
                        .setCreateBy(user.getRealname()).setGoodsSeriesId(group).setStatus(2);
                rsult = goodsMapper.insert(info);
                /*if (rsult > 0) {

                    // 统合表添加记录
                    goodsUtil.addTonghe(info.getId(), 0);
                }*/
            } else {
                // 更新操作
                info.setId(one.getId()).setUpdateBy(user.getRealname()).setGoodsSeriesId(group).setStatus(2);
                rsult = goodsMapper.updateById(info);
            }
        }
        return rsult;
    }

    /**
     * 获取商品删除模板（导出）
     *
     * @param groupID 系列id
     */
    @Override
    public List<GoodsParamExcel> exportGoodsParam(String groupID) {
        MlccThirdGoodsSeries series = goodsSeriesMapper.selectById(groupID);
        MlccThirdGoodsType type = goodsTypeMapper.selectById(series.getGoodsTypeId());
        QueryWrapper<MlccThirdGoodstypeParameter> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_type_id", type.getId());
        List<MlccThirdGoodstypeParameter> list = goodstypeParameterMapper.selectList(wrapper);
        GoodsParamExcel excel = new GoodsParamExcel();
        excel.setList(list);
        ArrayList<GoodsParamExcel> excels = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            excels.add(excel);
        }
        return excels;
    }

    /**
     * 商品参数导入
     *
     * @param list excel中的数据
     */
    @Override
    public int importGoodsParam(List<GoodsParamExcel> list) {
        // 如果是空文件
        if (list == null || list.size() == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int rsult = 0;
        for (GoodsParamExcel paramExcel : list) {
            List<MlccThirdGoodstypeParameter> paramList = paramExcel.getList();
            if (paramList != null && paramList.size() > 0) {
                // 遍历excel中配置的参数
                for (MlccThirdGoodstypeParameter parameter : paramList) {
                    QueryWrapper<MlccThirdGoods> wrapper = new QueryWrapper<>();
                    wrapper.eq("goods_code", paramExcel.getGoodsCode());
                    MlccThirdGoods goods = goodsMapper.selectOne(wrapper);
                    if (goods != null) {
                        // 查询类型参数的id
                        QueryWrapper<MlccThirdGoodstypeParameter> typeWrapper = new QueryWrapper<>();
                        typeWrapper.eq("parameter_name", parameter.getParameterName())
                                .eq("goods_type_id", goods.getGoodsTypeId());
                        // 拿到参数类型的参数，为了拿到id
                        MlccThirdGoodstypeParameter one = goodstypeParameterMapper.selectOne(typeWrapper);
                        if (one != null) {
                            QueryWrapper<MlccThirdGoodsandparameter> wrapper1 = new QueryWrapper<>();
                            wrapper1.eq("goods_id", goods.getId()).eq("parameter_id", one.getId());
                            // 是否能查询到具体的参数
                            MlccThirdGoodsandparameter goodsParam = goodsandparameterMapper.selectOne(wrapper1);
                            if (goodsParam != null) {
                                // 更新参数
                                goodsParam.setInputValue(parameter.getInputValue());
                                rsult = goodsandparameterMapper.updateById(goodsParam);
                            } else {
                                // 新增参数
                                MlccThirdGoodsandparameter goodsandparameter = new MlccThirdGoodsandparameter();
                                goodsandparameter.setId(UUID.randomUUID().toString()).setGoodsId(goods.getId())
                                        .setParameterId(one.getId() + "").setInputValue(parameter.getInputValue());
                                rsult = goodsandparameterMapper.insert(goodsandparameter);
                            }
                        }
                    }
                }
            }
        }
        return rsult;
    }

    /**
     * 商品册导入商品(把已有的商品加入商品册)
     *
     * @param list 上传的Excel文件数据
     */
    @Override
    public int importGoodstoBooklet(List<MlccThirdGoods> list, String bookletid) {
        // 如果是空文件
        if (list == null || list.size() == 0) {
            return 0;
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int rsult = 0;
        for (MlccThirdGoods info : list) {
            QueryWrapper<MlccThirdGoods> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("goods_code", info.getGoodsCode());
            MlccThirdGoods goods = goodsMapper.selectOne(wrapper1);
            if (goods != null) {
                // 查询商品册下是否已经有这个商品，防止重复添加
                QueryWrapper<MlccThirdGoodsAndBooklet> wrapper = new QueryWrapper<>();
                wrapper.eq("boolet_id", bookletid).eq("goods_id", goods.getId()).ne("status", 1);
                int count = goodsAndBookletMapper.selectCount(wrapper);
                if (count >= 1) {
                    // 商品已存在
                    continue;
                } else {
                    // 插入数据
                    MlccThirdGoodsAndBooklet booklet = new MlccThirdGoodsAndBooklet();
                    booklet.setGoodsId(goods.getId()).setBooletId(bookletid).setCreateBy(user.getRealname());
                    rsult = goodsAndBookletMapper.insert(booklet);
                }
            }
        }
        return rsult;
    }
}

